<template>
  <div>
    <h2 style="margin-bottom: 5px">套房管理</h2>
    <el-form
      :inline="true"
      :model="queryForm"
      :rules="rules"
      ref="queryForm"
      class="demo-form-inline"
    >
      <el-col :span="3">
        <el-form-item label="省" prop="province">
          <el-select @change="getCities" v-model="queryForm.province" placeholder="请选择省">
            <el-option
              v-for="item in provinces"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="3">
        <el-form-item label="市" prop="city">
          <el-select @change="getAreas" v-model="queryForm.city" placeholder="请选择市">
            <el-option
              v-for="item in cities"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="3">
        <el-form-item label="区域" prop="area">
          <el-select @change="getCommunities" v-model="queryForm.area" placeholder="请选择区域">
            <el-option
              v-for="item in areas"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="3">
        <el-form-item label="小区" prop="community">
          <el-select @change="getBuildings" v-model="queryForm.community" placeholder="请选择小区">
            <el-option
              v-for="item in communities"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="3">
        <el-form-item label="栋">
          <el-select v-model="queryForm.building" placeholder="请选择栋">
            <el-option
              v-for="item in buildings"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="3">
        <el-form-item label="状态">
          <el-select v-model="queryForm.status" placeholder="请选择状态">
            <el-option label="未发布" value="未发布"></el-option>
            <el-option label="已发布" value="已发布"></el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="3">
        <el-form-item label="房间号">
          <el-input v-model="queryForm.roomNumber" placeholder="请输入房间号"></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="3">
        <el-form-item>
          <p>点击查询</p>
          <el-button type="primary" @click="handleQuery">查询</el-button>
        </el-form-item>
      </el-col>
    </el-form>
    <el-button type="danger" @click="handleBatchDelete">批量删除</el-button>
    <el-button type="primary" @click="handleBatchPublish">批量发布</el-button>
    <el-button type="warning" @click="handleBatchRecycle">批量回收</el-button>
    <el-button type="success" @click="handleAddSuite">添加套房</el-button>
    <el-table
      @selection-change="handleSelectionChange"
      v-if="tableData.length > 0"
      :data="tableData"
      style="width: 100%"
    >
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column prop="roomNumber" label="套房号"></el-table-column>
      <el-table-column prop="area" label="面积"></el-table-column>
      <el-table-column prop="status" label="状态"></el-table-column>
      <el-table-column prop="image" label="图片">
        <template slot-scope="scope">
          <img :src="scope.row.image" alt="套房图片" style="width: 50px; height: 50px;" />
        </template>
      </el-table-column>
      <el-table-column prop="layout" label="户型"></el-table-column>
      <el-table-column label="操作" width="300">
        <template slot-scope="scope">
          <el-button-group>
            <el-button size="mini" type="warning" @click="handleEdit(scope.$index, scope.row)">修改</el-button>
            <el-button size="mini" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
            <el-button
              v-if="scope.row.status==='未发布'|| scope.row.status==='已回收'"
              size="mini"
              type="primary"
              @click="handlePublish(scope.$index, scope.row)"
            >发布</el-button>
            <el-button
              v-if="scope.row.status==='已发布'"
              size="mini"
              type="info"
              @click="handleRecycle(scope.$index, scope.row)"
            >回收</el-button>
            <el-button v-if="scope.row.status==='已租赁'" size="mini" type="info" disabled>禁用</el-button>
            <el-popover placement="left" width="210" trigger="click">
              <el-descriptions class="margin-top" title="套房详情" :column="1" size="mini" border>
                <template slot="extra">
                  <el-button
                    type="primary"
                    size="mini"
                    @click="handleEdit(scope.$index, scope.row)"
                  >编辑</el-button>
                </template>
                <el-descriptions-item label="ID">{{ scope.row.id }}</el-descriptions-item>
                <el-descriptions-item label="区域">{{ scope.row.areaName }}</el-descriptions-item>
                <el-descriptions-item label="小区">{{ scope.row.communityName }}</el-descriptions-item>
                <el-descriptions-item label="房号">{{ scope.row.roomNumber }}</el-descriptions-item>
                <el-descriptions-item label="面积">{{ scope.row.area }}</el-descriptions-item>
                <el-descriptions-item label="月租金">{{ scope.row.monthlyRent }}</el-descriptions-item>
                <el-descriptions-item label="状态">{{ scope.row.status }}</el-descriptions-item>
                <el-descriptions-item label="备注">{{ scope.row.remarks }}</el-descriptions-item>
                <el-descriptions-item label="户型">{{ scope.row.layout }}</el-descriptions-item>
                <el-descriptions-item label="图片">
                  <img :src="scope.row.image" alt="套房图片" style="width: 100px; height: 100px;" />
                </el-descriptions-item>
              </el-descriptions>
              <el-button size="mini" slot="reference">详情</el-button>
            </el-popover>
          </el-button-group>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      v-if="tableData.length > 0"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[5, 10, 15, 20]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
    ></el-pagination>
    <div v-else style="text-align: center; margin-top: 20px;">
      <el-empty description="暂无数据，请先进行查询"></el-empty>
    </div>
    <el-dialog :visible.sync="dialogVisible" title="添加套房">
      <el-form :model="form" :rules="addRules" ref="form">
        <el-form-item label="房号" prop="roomNumber">
          <el-input v-model="form.roomNumber"></el-input>
        </el-form-item>
        <el-form-item label="面积（平方米）" prop="area">
          <el-input v-model="form.area" type="number"></el-input>
        </el-form-item>
        <el-form-item label="租金（元）" prop="monthlyRent">
          <el-input v-model="form.monthlyRent" type="number"></el-input>
        </el-form-item>
        <el-form-item label="图片" prop="image">
          <br />
          <el-upload
            class="upload-demo"
            action="/public-rental-housing-ssm/upload"
            list-type="picture-card"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
            :before-upload="beforeUpload"
            :on-success="handleUploadSuccess"
            :limit="1"
            :on-exceed="handleExceed"
            :file-list="fileList"
            accept=".jpg, .jpeg, .png"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
          <el-dialog :visible.sync="imageDialogVisible">
            <img width="100%" :src="dialogImageUrl" alt />
          </el-dialog>
        </el-form-item>
        <el-col :span="6">
          <el-form-item label="房间数" prop="rooms">
            <el-select v-model="form.rooms" placeholder="请选择">
              <el-option
                v-for="item in roomOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="卫生间数" prop="bathrooms">
            <el-select v-model="form.bathrooms" placeholder="请选择">
              <el-option
                v-for="item in bathroomOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="厅数" prop="livingRooms">
            <el-select v-model="form.livingRooms" placeholder="请选择">
              <el-option
                v-for="item in hallOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="阳台数" prop="balconies">
            <el-select v-model="form.balconies" placeholder="请选择">
              <el-option
                v-for="item in balconyOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <p>备注</p><br>
        <el-input v-model="form.remarks"></el-input>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
  
  <script>
export default {
  data() {
    return {
      queryForm: {
        province: "",
        city: "",
        area: "",
        community: "",
        building: "",
        status: "",
        roomNumber: ""
      },
      tableData: [],
      currentPage: 1,
      pageSize: 5,
      total: "",
      provinces: [],
      cities: [],
      areas: [],
      communities: [],
      buildings: [],
      rules: {
        province: [{ required: true, message: "请选择省", trigger: "change" }],
        city: [{ required: true, message: "请选择市", trigger: "change" }],
        area: [{ required: true, message: "请选择区域", trigger: "change" }],
        community: [
          { required: true, message: "请选择小区", trigger: "change" }
        ]
      },
      dialogVisible: false,
      form: {
        areaName: "",
        communityName: "",
        roomNumber: "",
        area: "",
        monthlyRent: "",
        image: "",
        rooms: "",
        bathrooms: "",
        livingRooms: "",
        balconies: "",
        remarks: ""
      },
      roomOptions: [
        { value: 1, label: "1" },
        { value: 2, label: "2" },
        { value: 3, label: "3" }
      ],
      bathroomOptions: [
        { value: 1, label: "1" },
        { value: 2, label: "2" },
        { value: 3, label: "3" }
      ],
      hallOptions: [
        { value: 1, label: "1" },
        { value: 2, label: "2" },
        { value: 3, label: "3" }
      ],
      balconyOptions: [
        { value: 1, label: "1" },
        { value: 2, label: "2" },
        { value: 3, label: "3" }
      ],
      fileList: [],
      dialogImageUrl: "",
      imageDialogVisible: false,
      selectedRows: [],
      addRules: {
        roomNumber: [
          { required: true, message: "请输入房号", trigger: "blur" }
        ],
        area: [
          { required: true, message: "请输入面积", trigger: "blur" },
          { pattern: /^[0-9]+$/, message: "面积必须是数字", trigger: "blur" }
        ],
        monthlyRent: [
          { required: true, message: "请输入租金", trigger: "blur" },
          { pattern: /^[0-9]+$/, message: "租金必须是数字", trigger: "blur" }
        ],
        image: [{ required: true, message: "请上传图片", trigger: "change" }],
        rooms: [{ required: true, message: "请选择房间数", trigger: "change" }],
        bathrooms: [
          { required: true, message: "请选择卫生间数", trigger: "change" }
        ],
        livingRooms: [
          { required: true, message: "请选择厅数", trigger: "change" }
        ],
        balconies: [
          { required: true, message: "请选择阳台数", trigger: "change" }
        ]
      }
    };
  },
  methods: {
    handleQuery() {
      this.$refs.queryForm.validate(valid => {
        if (valid) {
          this.fetchData();
        } else {
          this.$message.error("请选择完整的查询条件");
          return false;
        }
      });
    },
    handleSelectionChange(val) {
      this.selectedRows = val;
    },
    handleBatchDelete() {
      if (this.selectedRows.length === 0) {
        this.$message.warning("请先选择要删除的房源");
        return;
      }
      this.$confirm("确定要删除选中的房源吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.$axios
            .post("apartment/delete", this.selectedRows)
            .then(res => {
              this.$message.info(res.data.message);
              this.fetchData();
            })
            .catch(err => {
              this.$message.error(err.message);
            });
        })
        .catch(() => {});
    },
    handleBatchPublish() {
      if (this.selectedRows.length === 0) {
        this.$message.warning("请先选择要发布的房源");
        return;
      }
      this.$axios
        .post("apartment/batchPublish", this.selectedRows)
        .then(res => {
          if (res.data.code === 200) {
            this.$alert(`以下套房发布成功！${res.data.data}`, "提示", {
              confirmButtonText: "确定",
              type: "success"
            });
            this.fetchData();
          } else {
            this.$message.error(res.data.message);
          }
        })
        .catch(err => {
          this.$message.error(err.message);
        });
    },
    handleBatchRecycle() {
      if (this.selectedRows.length === 0) {
        this.$message.warning("请先选择要回收的房源");
        return;
      }
      this.$confirm("确定要回收选中的房源吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.$axios
            .post("apartment/reclaim", this.selectedRows)
            .then(res => {
              this.$message.info(res.data.message);
              this.fetchData();
            })
            .catch(err => {
              this.$message.error(err.message);
            });
        })
        .catch(() => {});
    },
    handleAddSuite() {
      if (!this.queryForm.community) this.$message.warning("请先查询后操作");
      else {
        this.form = {};
        this.dialogVisible = true;
        this.fileList = [];
        this.form.areaName = this.queryForm.area;
        this.form.communityName = this.queryForm.community;
      }
    },
    handleEdit(index, row) {
      if (row.status === "已租赁") {
        this.$message.warning("已租赁的房源无法编辑");
        return;
      }
      this.form = { ...row };
      this.fileList = [{ name: row.image.split("/").pop(), url: row.image }];
      this.form.image = row.image.replace(
        "http://119.91.209.28:18008/public-rental-housing-ssm",
        ""
      );
      this.dialogVisible = true;
    },
    handleDelete(index, row) {
      this.$confirm("确定要删除该房源吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.$axios.post("apartment/delete", [row]).then(res => {
            this.$message.info(res.data.message);
            this.fetchData();
          });
        })
        .catch(() => {});
    },
    handlePublish(index, row) {
      this.$confirm("确定发布该房源吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.$axios
            .post("apartment/updateStatus", { status: "已发布", id: row.id })
            .then(res => {
              if (res.data.code === 200) {
                this.$message.success("发布成功");
                this.fetchData();
              } else {
                this.$message.error(res.data.message);
              }
            })
            .catch(err => {
              this.$message.error(err.message);
            });
        })
        .catch(() => {
          this.$message.info("已取消发布");
        });
    },
    handleRecycle(index, row) {
      this.$confirm("确定要回收该房源吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.$axios
            .post("apartment/reclaim", [row])
            .then(res => {
              this.$message.info(res.data.message);
              this.fetchData();
            })
            .catch(err => {
              this.$message.error(err.message);
            });
        })
        .catch(() => {});
    },
    handleSizeChange(size) {
      this.pageSize = size;
      this.fetchData();
    },
    handleCurrentChange(page) {
      this.currentPage = page;
      this.fetchData();
    },
    fetchData() {
      let curr =
        this.queryForm.roomNumber == ""
          ? (this.currentPage - 1) * this.pageSize
          : 0;
      this.$axios
        .post("apartment/query", {
          size: this.pageSize,
          curr,
          areaName: this.queryForm.area,
          communityName: this.queryForm.community,
          building: this.queryForm.building,
          roomNumber: this.queryForm.roomNumber,
          status: this.queryForm.status
        })
        .then(res => {
          if (res.data.code === 200) {
            this.tableData = res.data.data.map(apartment => {
              return {
                ...apartment,
                layout: `${apartment.rooms}房${apartment.livingRooms}厅${apartment.bathrooms}卫${apartment.balconies}阳`
              };
            });
            this.total = res.data.total;
          } else {
            this.$message.error(res.data.message);
          }
        })
        .catch(err => {
          this.$message.error(err.message);
        });
    },
    getProvinces() {
      this.$axios.post("area/province", { none: "none" }).then(res => {
        if (res.data.code === 200) {
          this.provinces = [];
          res.data.data.forEach(province => {
            this.provinces.push({ value: province.name, label: province.name });
          });
        } else {
          this.$message.error(res.data.message);
        }
      });
    },
    getCities() {
      this.queryForm.city = "";
      this.$axios
        .post("area/city", { province: this.queryForm.province })
        .then(res => {
          if (res.data.code === 200) {
            this.cities = [];
            res.data.data.forEach(city => {
              this.cities.push({ value: city.name, label: city.name });
            });
          } else {
            this.$message.error(res.data.message);
          }
        });
    },
    getAreas() {
      this.queryForm.area = "";
      this.$axios
        .post("area/query", {
          province: this.queryForm.province,
          city: this.queryForm.city,
          name: ""
        })
        .then(res => {
          if (res.data.code === 200) {
            this.areas = [];
            res.data.data.forEach(area => {
              this.areas.push({ value: area.name, label: area.name });
            });
          } else {
            this.$message.error(res.data.message);
          }
        });
    },
    getCommunities() {
      this.$axios
        .post("community/get", {
          area: this.queryForm.area,
          name: ""
        })
        .then(res => {
          if (res.data.code === 200) {
            this.communities = [];
            res.data.data.forEach(community => {
              this.communities.push({
                value: community.name,
                label: community.name
              });
            });
          } else {
            this.$message.error(res.data.message);
          }
        });
    },
    getBuildings() {
      this.$axios
        .post("apartment/building", {
          communityName: this.queryForm.community,
          areaName: this.queryForm.area
        })
        .then(res => {
          if (res.data.code === 200) {
            this.buildings = [];
            res.data.data.forEach(building => {
              this.buildings.push({ value: building, label: building });
            });
          } else {
            this.$message.error(res.data.message);
          }
        });
    },
    submitForm() {
      this.$refs.form.validate(valid => {
        if (valid) {
          this.$axios
            .post("apartment/addAn", this.form)
            .then(res => {
              if (res.data.code === 200) {
                this.$message.success("添加/修改成功");
                this.dialogVisible = false;
                this.fetchData();
              } else {
                this.$message.error(res.data.message);
              }
            })
            .catch(err => {
              this.$message.error(err.message);
            });
        } else {
          return false;
        }
      });
    },
    handleRemove(file, fileList) {
      this.$message.info("已移除图片");
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;

      this.imageDialogVisible = true;
    },
    beforeUpload(file) {
      const isJPG = file.type === "image/jpeg" || file.type === "image/png";
      const isLt500KB = file.size / 1024 < 500;

      if (!isJPG) {
        this.$message.error("上传图片只能是 JPG/PNG 格式!");
      }
      if (!isLt500KB) {
        this.$message.error("上传图片大小不能超过 500KB!");
      }
      return isJPG && isLt500KB;
    },
    handleExceed(files, fileList) {
      this.$message.warning("只能上传一张图片");
    },
    handleUploadSuccess(response, file, fileList) {
      this.form.image = response;
    }
  },
  mounted() {
    this.getProvinces();
    this.fetchData();
  }
};
</script>
  
  <style scoped>
  
</style>
  